package com.hyjiacan.tools.apps.dbm.handlers

import com.hyjiacan.tools.apps.dbm.models.DbmRequestForm
import com.hyjiacan.tools.apps.dbm.models.ConnectionModel
import com.hyjiacan.tools.apps.dbm.services.ConnectionService
import com.hyjiacan.tools.apps.dbm.utils.Misc
import com.hyjiacan.tools.apps.dbm.utils.MySQL
import com.hyjiacan.tools.http.entities.QueryResult
import com.hyjiacan.tools.http.handlers.AjaxHandler
import com.hyjiacan.tools.http.models.RequestContext

class ConnectionHandler : AjaxHandler() {
    /**
     * 获取存储的所有连接信息
     */
    override fun get(request: RequestContext): Any {
        val result = QueryResult()
        try {
            result.data = ConnectionService.all()
            result.success = true
        } catch (e: Exception) {
            result.success = false
            result.message = e.message
        }
        return result
    }

    /**
     * 保存（新增或更新）一个连接信息
     */
    override fun post(request: RequestContext): Any {
        val result = QueryResult()
        try {
            val connection = getConnection(request)
            ConnectionService.set(connection)
            result.success = true
        } catch (e: Exception) {
            result.success = false
            result.message = e.message
        }
        return result
    }

    /**
     * 测试连接信息是否可用
     */
    override fun put(request: RequestContext): Any {
        val form = DbmRequestForm(request.form)
        return MySQL.execute(form.options, "select 1", 0, 0)
    }

    /**
     * 删除一个存储的连接信息
     */
    override fun delete(request: RequestContext): Any {
        val result = QueryResult()
        try {
            ConnectionService.remove(request.params["id"]!!.toInt())
            result.success = true
        } catch (e: Exception) {
            result.success = false
            result.message = e.message
        }
        return result
    }


    /**
     * 从请求参数中解析出数据库连接信息
     */
    @Throws(Exception::class)
    private fun getConnection(request: RequestContext): ConnectionModel {
        val form = DbmRequestForm(request.form)
        return Misc.decodeOption(form.options)
    }
}